# This script will run a BRT model, with parameters defined by argument created in the submission script
# Then it will produce summaries and plots of the model
# NB BRT Source Functions must be located in the working directory

# Obtain command line arguments from .sh file

args=(commandArgs(TRUE))

# Evaluate the arguments for use in this script

for(i in 1:length(args)) 
	
	{
		
	eval(parse(text=args[[i]]))
 
	}
	
### Manual parameter definition, comment out before submitting to batch

#lr = .05;tc = 16;tf = 1;nt = 10000;i=1;out.dir = '/home1/99/jc152199/brt/FINALOPTIMALMODELS/'
	
# Load Elith Source Code

setwd('/home1/99/jc152199/brt/')
source('brt.functions.R.cjsedit.r')

# Establish directories

in.dir = '/home1/99/jc152199/brt/data/'

out.dir = paste(output.dir,sep='')

setwd(out.dir)

# Load gbm library

library('gbm')

# Read in data to model

model.data = read.csv('/home1/99/jc152199/MicroclimateStatisticalDownscale/ToAnalyse/Model_Data.csv',header=T)

# Randomly shuffle model.data before subsetting to training/testing sets

model.data = model.data[c(sample(c(1:nrow(model.data)), nrow(model.data),replace=FALSE)),]

# Randomly sample half of data set to produce a training and a testing set

sample.vector = c(sample(c(1:nrow(model.data)), round(nrow(model.data)*as.numeric(tf),0),replace=FALSE))

train.data = model.data[c(sample.vector),]
test.data = model.data[-c(sample.vector),]

# Run BRT model using gbm.step, parameters are defined as arguments

max.brt.gbm.step = gbm.step(data=train.data,gbm.x = c(6:15),gbm.y = 4,max.trees=as.numeric(nt),family = "gaussian",tree.complexity = as.numeric(tc), learning.rate = as.numeric(lr) ,bag.fraction = 0.5, n.folds=10)

min.brt.gbm.step = gbm.step(data=train.data,gbm.x = c(6:15),gbm.y = 3,max.trees=as.numeric(nt),family = "gaussian",tree.complexity = as.numeric(tc), learning.rate = as.numeric(lr) ,bag.fraction = 0.5, n.folds=10)

# Save model

save(max.brt.gbm.step, file=paste(out.dir,'OptimalMaxModel.Rdata',sep=''))
save(min.brt.gbm.step, file=paste(out.dir,'OptimalMinModel.Rdata',sep=''))

# Assemble a model summary dataframe

mod.sum = data.frame(learning.rate = lr, tree.complexity = tc, max.dev = max.brt.gbm.step$cv.statistics$deviance.mean, max.se = max.brt.gbm.step$cv.statistics$deviance.se, min.dev = min.brt.gbm.step$cv.statistics$deviance.mean, min.se = min.brt.gbm.step$cv.statistics$deviance.se)


# Append preds to model data

train.data$min_preds = min.brt.gbm.step$fitted
train.data$max_preds = max.brt.gbm.step$fitted

# Write model data to the out directory

write.csv(train.data, file=paste(out.dir,'Model_Data_Plus_Preds.csv',sep=''),row.names=F)
write.csv(test.data, file=paste(out.dir,'Test_Data.csv',sep=''),row.names=F)

# Done


